<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/1/23
 * Time: 上午10:34
 */

namespace App\Http\Model;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Teenager extends Base
{
    protected $table_teenager = "user_teenager";
    private $redisUserTeenager = 'CACHE:USER:TEENAGER';

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**设置锁
     * @param $data
     * @return int
     */
    public function setLock($data){
        $res = $this->getLockInfo($data['user_id']);
        if (!empty($res)){
            DB::table($this->table_teenager)
                ->where('user_id' ,$data['user_id'])
                ->update(array('password'=>$data['password'] ,'switch'=>1));
        }else{
            $res = DB::table($this->table_teenager)->insertGetId($data);
        }
        if($res){
            Redis::HSET($this->redisUserTeenager ,$data['user_id'] ,1);
        }
        return $res;
    }

    /**获取锁
     * @param $user_id
     * @return int
     */
    public function getLock($user_id){
        $lock = Redis::HGET($this->redisUserTeenager ,$user_id);
        if($lock === null){
            $res = DB::table($this->table_teenager)
                ->where('user_id' ,$user_id)
                ->first();
            $res = $this->objToArray($res);
            if(empty($res) || $res['switch'] == 0){
                $lock = 0;
            }else{
                $lock = 1;
            }
            Redis::HSET($this->redisUserTeenager ,$user_id ,$lock);
        }
        return $lock ?? 0;
    }

    /**获取加锁信息
     * @param $user_id
     * @return mixed
     */
    public function getLockInfo($user_id){
        $res = DB::table($this->table_teenager)
            ->where('user_id' ,$user_id)
            ->first();
        return $this->objToArray($res);
    }

    /**解锁/加锁
     * @param $user_id
     * @param $switch
     */
    public function unlocking($user_id ,$switch){
        $res = DB::table($this->table_teenager)
            ->where('user_id' ,$user_id)
            ->update(array('switch'=>$switch ,'updated_at'=>date('Y-m-d H:i:s')));
        if($res){
            Redis::HSET($this->redisUserTeenager ,$user_id ,$switch);
        }
    }
}
